package bmatch.tech.todo.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Calendar;
import java.util.Date;

/**
 * @program:todo
 * @author:LinJinhao
 * @create:2019-01-02 20:57
 **/
public class JwtUtils {
	private static Logger log = LoggerFactory.getLogger(JwtUtils.class);

	private static Algorithm algorithm = Algorithm.HMAC256("secret");

	public static String generator(String userId) {
		//过期信息
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DAY_OF_YEAR, 3);
		Date d2 = calendar.getTime();

		try {
			//创建一个Token 包含用户id信息
			String token = JWT.create()
					.withIssuer("bmatch")
					.withJWTId(userId)
					.withClaim("admin", "false")
					.withExpiresAt(d2)
					.sign(algorithm);
			return token;
		} catch (Exception e) {
			log.error("", e);
			return null;
		}
	}

	/**
	 * 解析
	 * @param token
	 */
	public static String parse(String token) {
		JWTVerifier verifier = JWT.require(algorithm).withIssuer("bmatch").build();
		DecodedJWT decodedJWT = verifier.verify(token);
		String admin = decodedJWT.getClaim("admin").asString();
		String id = decodedJWT.getId();
		return id;
	}
}
